import React from 'react';
import { Card, Form, Table, Modal } from 'antd';
import { get as getPath } from 'object-path';
import { Pagination } from '@/components';
import { connect } from 'umi';
import moment from 'moment';
import { formatMessage } from 'umi';
import LinkTo from '@/components/LinkTo';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DataPick2 from '@/components/DatePicker2';
import { dateConversion2 } from '@/utils/utils';
import { withRoutePage } from '@/utils/enhanceUtils';

class OutList extends React.Component {
    state = {
        orderByField: '',
        dateOption: [
            {
                en: 'year',
                cn: '今年'
            },
            {
                en: 'month',
                cn: '本月'
            },
            {
                en: 'week',
                cn: '本周'
            }
        ],
        times: [
            moment(
                moment()
                    .month(moment().month())
                    .startOf('month')
                    .format('YYYY-MM-DD')
            ),
            moment()
        ],
        visible: false,
        signDate: '',
        columnsModal: [
            {
                title: '工号',
                dataIndex: 'userNo',
                key: 'userNo'
            },
            {
                title: '打卡时间',
                dataIndex: 'attDatetime',
                key: 'attDatetime'
            },
            {
                title: '考勤来源',
                dataIndex: 'deviceName',
                key: 'deviceName'
            }
        ],
        sorters: ''
    };

    componentDidMount() {
        const { times } = this.state;
        if (getPath(this.props, 'location.query.date')) {
            const date = [
                moment(
                    moment(getPath(this.props, 'location.query.date'))
                        .startOf('month')
                        .format('YYYY-MM-DD')
                ),
                moment(
                    moment(getPath(this.props, 'location.query.date'))
                        .endOf('month')
                        .format('YYYY-MM-DD')
                )
            ];
            this.handleSearch(date);
        } else {
            this.handleSearch(times);
        }
    }

    componentWillUnmount() {
        const {
            dispatch,
            overtimeList: { pagination: curPagination }
        } = this.props;

        dispatch({
            type: 'overtimeList/setPagination',
            pagination: {
                ...curPagination,
                pageSize: 10,
                current: 1
            }
        });
    }

    handleSearch = (v, type) => {
        this.setState(
            {
                times: v
            },
            () => {
                this.fetchList(getPath(type, ''));
            }
        );
    };

    // 获取列表
    fetchList = type => {
        const { times } = this.state;
        const {
            dispatch,
            overtimeList: { pagination }
        } = this.props;
        const user = JSON.parse(localStorage.getItem('user'));
        const parame = {
            employeeCode: getPath(user, 'employeeCode', ''),
            startTime: times[0].format('YYYY-MM-DD'),
            endTime: times[1].format('YYYY-MM-DD'),
            pageNo: type ? 1 : pagination.current,
            pageSize: pagination.pageSize,
            orderByField: getPath(this.state, 'orderByField', '')
        };
        dispatch({
            type: 'overtimeList/fetchMyout',
            payload: parame
        });
    };

    showModal = () => {
        this.setState({
            visible: true
        });
    };

    setVisible = type => {
        this.setState({
            visible: type
        });
    };

    // 打卡记录
    seeDetail = record => {
        const { dispatch } = this.props;
        const user = JSON.parse(localStorage.getItem('user'));
        const parame = {
            employeeCode: getPath(user, 'employeeCode', ''),
            startTime: moment(record.startTime).format('YYYY-MM-DD'),
            endTime: moment(record.endTime).format('YYYY-MM-DD'),
            pageNo: 1,
            pageSize: 10
        };
        dispatch({
            type: 'overtimeList/fetchMydetail',
            payload: parame
        }).then(() => {
            this.setState({
                signDate: moment(record.startTime).format('YYYY-MM-DD')
            });
            this.showModal();
        });
    };

    // 表格表头点击切换排序
    changeTable = async (pagination, filters, sorter) => {
        let orderBy;
        let sorterField;
        if (sorter && sorter.field && sorter.order) {
            if (sorter.field === 'startTime') {
                sorterField = 'start_time';
            }
            if (sorter.field === 'endTime') {
                sorterField = 'end_time';
            }
            if (sorter.field === 'outLong') {
                sorterField = 'out_long';
            }
            const order = sorter.order.trim().split('end')[0];
            orderBy = `${sorterField} ${order}`;
            this.setState({
                orderByField: orderBy
            });
        } else {
            this.setState({
                orderByField: ''
            });
        }
        const { dispatch, overtimeList } = this.props;
        const { sorters } = this.state;
        await dispatch({
            type: 'overtimeList/setPagination',
            pagination: {
                ...overtimeList.pagination,
                ...pagination
            }
        });
        if (sorter && sorters !== sorter) {
            this.setState({
                sorters: sorter
            });
            await dispatch({
                type: 'overtimeList/setPagination',
                pagination: {
                    ...overtimeList.pagination,
                    current: 1
                }
            });
        }
        this.fetchList();
    };

    render() {
        const { loading, overtimeList } = this.props;
        const { outData, pagination, attenddetail } = overtimeList;
        const { dateOption, signDate, columnsModal, visible } = this.state;
        let defaultDate;
        if (getPath(this.props, 'location.query.date') && getPath(this.props, 'location.query.date') !== 'undefined') {
            defaultDate = getPath(this.props, 'location.query.date');
        }
        const columnsList2 = [
            {
                title: `${formatMessage({
                    id: 'stat.out.startTime'
                })}`,
                dataIndex: 'startTime',
                key: 'startTime',
                sorter: () => {}
            },
            {
                title: `${formatMessage({
                    id: 'stat.out.endTime'
                })}`,
                dataIndex: 'endTime',
                key: 'endTime',
                sorter: () => {},
                render: (text, record) => <span>{record.endTime ? record.endTime : '--'}</span>
            },
            {
                title: `${formatMessage({
                    id: 'stat.out.outLong'
                })}`,
                dataIndex: 'outLong',
                key: 'outLong',
                render: (text, record) => <span>{record.outLong ? dateConversion2(record.outLong) : '--'}</span>,
                sorter: () => {}
            },
            {
                title: `${formatMessage({
                    id: 'stat.out.outReason'
                })}`,
                dataIndex: 'outReason',
                key: 'outReason',
                width: 150,
                render: (text, record) => (
                    <p
                        style={{
                            width: '150px',
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            marginBottom: '0'
                        }}
                        title={record.outReason}
                    >
                        {record.outReason}
                    </p>
                )
            },
            {
                title: `${formatMessage({
                    id: 'stat.miss.applicationNo'
                })}`,
                dataIndex: 'applicationNo',
                key: 'applicationNo',
                render: (text, record) => {
                    const { applicationNo } = record;
                    const isOldFlow = !applicationNo.includes('-');
                    const url = isOldFlow
                        ? '/personal/portal/flow/mine/myApplication/detail'
                        : '/personal/portal/myApplication/detail';
                    const params = { applicationNo };

                    return (
                        <span>
                            {/* <Link
                                to={{
                                    pathname:
                                        '/personal/flow/mine/myApplication/detail',
                                    query: {
                                        applicationNo: record.applicationNo
                                    }
                                }}
                            >
                                {record.applicationNo}
                            </Link> */}
                            <LinkTo to={url} query={params}>
                                {applicationNo}
                            </LinkTo>
                        </span>
                    );
                }
            },

            {
                title: `${formatMessage({
                    id: 'stat.absence.action'
                })}`,
                dataIndex: 'action',
                key: 'action',
                render: (text, record) => (
                    <a onClick={() => this.seeDetail(record)}>
                        {formatMessage({
                            id: 'stat.absence.seeDetail'
                        })}
                    </a>
                )
            }
        ];

        return (
            <PageHeaderWrapper>
                <Card
                    title={formatMessage({
                        id: 'stat.out.title'
                    })}
                    bordered={false}
                    extra={
                        <DataPick2
                            onSearch={v => {
                                this.handleSearch(v, 'out', true);
                            }}
                            dateOption={dateOption}
                            mode="month"
                            defaultDate={defaultDate}
                        />
                    }
                >
                    <Table
                        bordered={false}
                        dataSource={outData}
                        columns={columnsList2}
                        loading={loading}
                        rowKey="id"
                        onChange={this.changeTable}
                        pagination={false}
                    />
                    <Pagination {...pagination} onChange={this.changeTable} loading={loading} />
                    <Modal
                        title={
                            <div>
                                <div style={{ fontSize: '20px', color: '#333' }}>
                                    {formatMessage({
                                        id: 'stat.ckdkjl'
                                    })}
                                </div>
                                <p
                                    style={{
                                        color: 'rgba(0, 0, 0, .45)',
                                        fontSize: '14px',
                                        marginBottom: 0
                                    }}
                                >
                                    {signDate}
                                    {formatMessage({
                                        id: 'stat.dksj'
                                    })}
                                </p>
                            </div>
                        }
                        width={600}
                        footer={null}
                        visible={visible}
                        onOk={() => this.setVisible(false)}
                        onCancel={() => this.setVisible(false)}
                        centered
                    >
                        <Table
                            dataSource={attenddetail}
                            columns={columnsModal}
                            pagination={false}
                            loading={loading}
                            rowKey="id"
                        />
                    </Modal>
                </Card>
            </PageHeaderWrapper>
        );
    }
}

export default withRoutePage(
    connect(({ overtimeList, loading }) => ({
        overtimeList,
        loading: loading.models.overtimeList
    }))(Form.create()(OutList))
);
